package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-05-21
 * Time: 21:50
 */
public class Demo11 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            //哪个线程中调用currentThread方法就获取到哪个线程中Thread的引用
            while (/*不能用thread的原因还是因为lambda定义在new thread之前 也是在声明thread之前*/
            !Thread.currentThread().isInterrupted()) {
                System.out.println("hello thread");
                try {
                    Thread.sleep(1000);//当执行到interrupt时这里被唤醒异常就会执行catch
                    //sleep被唤醒interrupt之后isInterrupt会由true继续变为false
                } catch (InterruptedException e) {
                    //可以自行决定线程什么时候结束
                    //1.加上break是立即终止
                    //2.啥也不写 就是不终止
                    //3.catch中先执行一些其他逻辑再break 就是稍后终止
                    break;
                }
            }
            System.out.println("thread线程结束");
        });

        thread.start();

        Thread.sleep(3000);
        System.out.println("main线程尝试终止");
        /**
         * interrupt
         * 主动去终止修改boolean变量值
         * 除了设置boolean变量之外还能唤醒像sleep的阻塞方法
         */
        thread.interrupt();//将boolean改成true

        //System.out.println("main: " + Thread.currentThread().getName());//获取当前线程的名字
    }
}
